package com.ysxsoft.wdg.ui.activity.shopcart;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.classic.common.MultipleStatusView;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.ShopcartConfirmAdapter;
import com.ysxsoft.wdg.adapter.order.ZyOrderDetailActivity;
import com.ysxsoft.wdg.base.BaseActivity;
import com.ysxsoft.wdg.bean.AddressBean;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.cart.ShopcartConfirmBean;
import com.ysxsoft.wdg.bean.zy.CreateIdBean;
import com.ysxsoft.wdg.bean.event.CommentEvent;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.pay.PayListenerUtils;
import com.ysxsoft.wdg.pay.PayPopWindow;
import com.ysxsoft.wdg.pay.PayResultListener;
import com.ysxsoft.wdg.pay.PayUtils;
import com.ysxsoft.wdg.pay.WxPayBean;
import com.ysxsoft.wdg.ui.activity.address.AddressListActivity;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.ysxsoft.wdg.widget.alertview.AlertUtils;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import static com.ysxsoft.wdg.bean.event.CommentEvent.EventStatus.CART_upadata;

public class ShopcartConfirmActivity extends BaseActivity implements PayResultListener {


    public static void start(Context context, String cardid,int num) {
        Intent intent = new Intent(context, ShopcartConfirmActivity.class);
        intent.putExtra("cardid", cardid);
        intent.putExtra("num", num);
        context.startActivity(intent);
    }


    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.rl_add_address)
    RelativeLayout rlAddAddress;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address_address)
    TextView tvAddressAddress;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.ll_address_has)
    LinearLayout llAddressHas;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.tv_yun)
    TextView tvYun;
    @BindView(R.id.tv_total_num)
    TextView tvTotalNum;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private PayPopWindow payPopWindow;
    private ShopcartConfirmAdapter adapter;
    private String cardid = "", uid = "", addressId = "",num = "", acount = "",yuE = "",orderId = "",yun = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shopcart_confirm;
    }

    @Override
    protected void initData() {
        initStatusBar(topView, false);
        titleContent.setText("确认订单");
        recyclerview.setFocusable(false);
        recyclerview.setNestedScrollingEnabled(false);

        uid = SharePrefUtils.getUserId();
        cardid = getIntent().getStringExtra("cardid");
        num = getIntent().getIntExtra("num",1)+"";
        tvTotalNum.setText("共"+num+"件商品  合计");

        adapter = new ShopcartConfirmAdapter(R.layout.include_order_goods);
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        recyclerview.setAdapter(adapter);
        PayListenerUtils.getInstance(ShopcartConfirmActivity.this).addListener(this);
        getData();
    }

    private void getData() {
        mApiHelper.sureCartOrder(uid, cardid, new Observer<BaseBean<ShopcartConfirmBean>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<ShopcartConfirmBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    ShopcartConfirmBean confirmBean = baseBean.getData();
                    AddressBean addressBean = confirmBean.getAddress();

                    if (addressBean != null) {
                        llAddressHas.setVisibility(View.VISIBLE);
                        rlAddAddress.setVisibility(View.GONE);
                        tvAddressName.setText(addressBean.getName());
                        tvAddressPhone.setText(addressBean.getPhone());
                        tvAddressAddress.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getCounty() + addressBean.getAddress());
                        addressId = addressBean.getId();
                    } else {
                        llAddressHas.setVisibility(View.GONE);
                        rlAddAddress.setVisibility(View.VISIBLE);
                    }

                    adapter.setNewData(confirmBean.getGoods());
                    yun = confirmBean.getYun();
                    tvYun.setText(yun);
                    acount = confirmBean.getTotal();
                    tvTotalMoney.setText(acount);

                } else {
                    ToastUtils.showToast(baseBean.getMs());
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void setListener() {
        PayListenerUtils.getInstance(mContext).addListener(this);
    }

    @OnClick({R.id.title_finish, R.id.ll_address, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_finish:
                finish();
                break;
            case R.id.ll_address:
                toAddressListActivity();
                break;
            case R.id.btn_commit:
                if (TextUtils.isEmpty(addressId)) {
                    ToastUtils.showToast("请选择收货地址");
                    return;
                }
                if (TextUtils.isEmpty(orderId) || TextUtils.isEmpty(yuE)) {
                    createOrder();
                }else {
                    showPayWindow();
                }
                break;
        }
    }

    private void createOrder() {
        mApiHelper.createCartOrder(uid, cardid, addressId, acount, yun, new Observer<BaseBean<CreateIdBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<CreateIdBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    EventBus.getDefault().post(new CommentEvent(CART_upadata));
                    CreateIdBean idBean = baseBean.getData();
                    orderId = idBean.getOrderid();
                    yuE = idBean.getYu();
                    showPayWindow();
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.showToast("请稍后再试");
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void showPayWindow() {
        if (payPopWindow != null) {
            payPopWindow.dismiss();
            payPopWindow = null;
        }

        payPopWindow = new PayPopWindow(this, acount, yuE);
        payPopWindow.show(mRootView);

        payPopWindow.setOnPayLiatener(new PayPopWindow.OnPayLiatener() {
            @Override
            public void payType(int payType) {//payment= "3";//支付方式 1=>微信 2=>支付宝 3=>账户余额 4=>积分支付
                AlertUtils.payAlert((Activity) mContext);
                switch (payType) {
                    case 0://余额支付
                        postPayYue();
                        break;
                    case 1://支付宝支付
                        postPayZfb();
                        break;
                    case 2://微信支付
                        postPayWx();
                        break;
                }
            }
        });
    }

    private void postPayWx() {
        mApiHelper.payZyWx(uid, orderId, acount, "0", new Observer<BaseBean<WxPayBean>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<WxPayBean> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
//                    PayUtils.getInstance(mContext).pay((Activity) mContext, PayUtils.PAY_TYPE_WX,"",baseBean.getData());
                    PayUtils.getInstance(ShopcartConfirmActivity.this).toWxPay(baseBean.getData());
                }else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void postPayZfb() {
        mApiHelper.payZyZfb(uid, orderId, acount, "0", new Observer<BaseBean<String>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean<String> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    PayUtils.getInstance(mContext).pay((Activity) mContext,
                            PayUtils.PAY_TYPE_ALI,baseBean.getData(),null);
                }else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void postPayYue() {
        mApiHelper.payZyYue(uid, orderId, acount, "0", new Observer<BaseBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseBean baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)){
                    PayListenerUtils.getInstance(mContext).addSuccess();
                }else {
                    ToastUtils.showToast(baseBean.getMs());
                    AlertUtils.dismissAlert();
                }
            }

            @Override
            public void onError(Throwable e) {
                PayListenerUtils.getInstance(mContext).addError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    public void onPaySuccess() {
        ToastUtils.showToast("支付成功");
        toOrderDetail();
    }

    @Override
    public void onPayError() {
        ToastUtils.showToast("支付失败");
        toOrderDetail();
    }

    @Override
    public void onPayCancel() {

        ToastUtils.showToast("取消支付");
        toOrderDetail();
    }

    private void toOrderDetail() {
        AlertUtils.dismissAlert();

        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                ZyOrderDetailActivity.start(mContext,orderId,true);
            }
        });
        finish();
    }


    //选择地址
    private void toAddressListActivity() {
        Intent intent = new Intent(this, AddressListActivity.class);
        intent.putExtra("code", 1);
        startActivityForResult(intent, AddressListActivity.ADDRESS_CHOOSE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AddressListActivity.ADDRESS_CHOOSE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    llAddressHas.setVisibility(View.VISIBLE);
                    rlAddAddress.setVisibility(View.GONE);
                    AddressBean item = data.getParcelableExtra("address");
                    addressId = item.getId() + "";
                    tvAddressAddress.setText(item.getAddress());
                    tvAddressName.setText(item.getName());
                    tvAddressPhone.setText(item.getPhone());
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        PayListenerUtils.getInstance(mContext).removeListener(this);
        super.onDestroy();
    }

}
